import Vue from 'vue'
import Vuex from 'vuex'
import { apiClient } from '@/util/apiClient'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        fields: {
            newItem: '',
            email: '',
            urgency: '',
            termsAndConditions: false
        },
        items: []
    },
    mutations: {
        UPDATE_INPUT (state, val) {
            state.fields.newItem = val
        },
        UPDATE_NEW_ITEM (state, payload) {
            state.fields.newItem = payload
        },
        UPDATE_EMAIL (state, payload) {
            state.fields.email = payload
        },
        UPDATE_URGENCY (state, payload) {
            state.fields.urgency = payload
        },
        UPDATE_TERMS_AND_CONDITIONS (state, payload) {
            state.fields.termsAndConditions = payload
        },
        UPDATE_ITEMS (state, payload) {
            console.log("UPDATE_ITEMS",payload);
            state.items = payload
        },
        CLEAR_FIELDS (state) {
            console.log("CLEAR_FIELDS");
            state.fields.newItem = ''
            state.fields.email = ''
            state.fields.urgency = ''
            state.fields.termsAndConditions = false
        }
    },
    actions: {
        loadItems (context, payload) {
            return new Promise((resolve, reject) => {
                apiClient.loadItems().then((items:any) => {
                    context.commit('UPDATE_ITEMS', items);
                    resolve(items);
                });
            }).catch((error) =>{
                console.log(error);
            });
        },
        saveItems(context,payload){
            return new Promise((resolve, reject) => {
                const items = payload;
                apiClient.saveItems(items).then((response) =>{
                    context.commit("UPDATE_ITEMS",items);
                    context.commit("CLEAR_FIELDS");
                    resolve(items);
                },(error) =>{
                    reject(error);
                })
            });
        }
    },
    modules: {},
    getters: {
        newItem:state => state.fields.newItem,
        newItemLength:state => state.fields.newItem.length,
        isNewItemInputLimitExceeded:state => state.fields.newItem.length >= 20,
        email:state => state.fields.email,
        urgency:state => state.fields.urgency,
        isNotUrgency:state => state.fields.urgency === "Nonessential",
        termsAndConditions:state => state.fields.termsAndConditions,
        items:state => state.items
    }
})
